package com.huanwei.rizhi;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnChangeLisener;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.github.czy1121.view.RoundButton;
import com.huanwei.mini.R;
import com.huanwei.mini.adapter.FullyGridLayoutManager;
import com.huanwei.mini.adapter.GridImageAdapter;
import com.huanwei.mini.http.API;
import com.huanwei.mini.http.Photo_Bean;
import com.huanwei.mini.http.RenYuan;
import com.huanwei.mini.http.Rizhi;
import com.huanwei.mini.utils.JSONUtils;
import com.huanwei.mini.utils.Okhttp;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.DebugUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//https://github.com/LuckSiege/PictureSelector
public class RizhiActivity extends AppCompatActivity {
    String shijian;
    @BindView(R.id.riqi)
    TextView riqi;
    @BindView(R.id.shijian_riqi)
    LinearLayout shijianRiqi;
    @BindView(R.id.img_back)
    RelativeLayout imgBack;
    @BindView(R.id.textView18)
    TextView textView18;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.spinner)
    MaterialSpinner spinner;
    @BindView(R.id.tv_zhongzhuanzhan)
    TextView tvZhongzhuanzhan;
    @BindView(R.id.tv_zhuti)
    EditText tvZhuti;
    @BindView(R.id.tv_jinzhanyaodian)
    EditText tvJinzhanyaodian;
    @BindView(R.id.tv_wt)
    TextView tvWt;
    @BindView(R.id.tv_beizhu)
    EditText tv_beizhu;
    @BindView(R.id.save_address)
    RoundButton saveAddress;
    @BindView(R.id.recycler)
    RecyclerView recycler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rizhi2);
        ButterKnife.bind(this);
        Date date = new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, 1);//把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(date);
        shijian = dateString;
        riqi.setText(dateString);
        shijianRiqi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDatePickDialog();

            }
        });
        initview();
        getdata();

    }

    private void showDatePickDialog() {
        DatePickDialog dialog = new DatePickDialog(this);
        //设置上下年分限制
        dialog.setYearLimt(5);
        //设置标题
        dialog.setTitle("选择时间");
        //设置类型
        dialog.setType(DateType.TYPE_YMD);
        //设置消息体的显示格式，日期格式
        dialog.setMessageFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, 0);//把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime();
        dialog.setStartDate(date);
        //设置选择回调
        dialog.setOnChangeLisener(new OnChangeLisener() {
            @Override
            public void onChanged(Date date) {

            }
        });
        //设置点击确定按钮回调
        dialog.setOnSureLisener(new OnSureLisener() {
            @Override
            public void onSure(Date date) {
                Log.e("111", "xx" + date);


                // 这里也个用SimpleDateFormat的format（）进行格式化，然后以字符串形式返回格式化后的date

                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = dateFormat.format(date);

                riqi.setText(format);
                shijian = format;
            }


        });
        dialog.show();
    }

    public void getdata() {
        API.Getuser(RizhiActivity.this, new Okhttp.Objectcallback() {
            @Override
            public void onsuccess(String st) {
                Log.e("zzz", "xx" + st);
                RenYuan renYuan = JSONUtils.parseJSON(st, RenYuan.class);
//                if (renYuan.getError()==0) {
//                    datashijian = renYuan.getData();
//
//                    if (datashijian != null && datashijian.size() != 0) {
//
//                        ccList2.clear();
//                        for (int i = 0; i < datashijian.size(); i++) {
//                            ccList2.add(datashijian.get(i).getTimeSpan());
//                        }
//                        spinnershijian.setItems(ccList2);
//                        shijianid = "" + datashijian.get(0).getId();
//                        shijianname = datashijian.get(0).getTimeSpan();
//
//                    }
//                } else {
//                    Toast.makeText(RizhiActivity.this, ""+renYuan.getMsg(), Toast.LENGTH_SHORT).show();
//                }

            }

            @Override
            public void onFalia(int code, String errst) {

            }
        });
    }

    private List<LocalMedia> selectList = new ArrayList<>();
    GridImageAdapter adapter;
    int themeId;
    LocalMedia media;

    private void initview() {
        themeId = R.style.picture_default_style;
        FullyGridLayoutManager manager = new FullyGridLayoutManager(RizhiActivity.this, 4, GridLayoutManager.VERTICAL, false);
        recycler.setLayoutManager(manager);
        adapter = new GridImageAdapter(RizhiActivity.this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(5);
        recycler.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(RizhiActivity.this).externalPicturePreview(position, selectList);
                            break;


                    }
                }
            }
        });


    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {


            // 进入相册 以下是例子：不需要的api可以不写
            PictureSelector.create(RizhiActivity.this)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                    .maxSelectNum(5)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(4)// 每行显示个数
                    .selectionMode(
                            PictureConfig.MULTIPLE)// 多选 or 单选
                    .previewImage(true)// 是否可预览图片
                    .compressGrade(Luban.THIRD_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                    .enableCrop(false)// 是否裁剪
                    .compress(true)// 是否压缩
                    .compressMode(PictureConfig.LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                    .selectionMedia(selectList)// 是否传入已选图片
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }


    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的

                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    DebugUtil.i("3344", "onActivityResult:" + selectList.size());
                    break;

            }
        }
    }

    Photo_Bean photo;
    String jsosns;
    ArrayList<Photo_Bean> photo_been = new ArrayList<Photo_Bean>();

    public void shangchuan() {
        if (TextUtils.isEmpty(tvZhuti.getText().toString())) {
            Toast.makeText(this, "请填写主题", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(tv_beizhu.getText().toString())) {
            Toast.makeText(this, "请填写备注", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(tvJinzhanyaodian.getText().toString())) {
            Toast.makeText(this, "请填写进展", Toast.LENGTH_SHORT).show();
            return;
        }
        for (int i = 0; i < selectList.size(); i++) {
            String compressPath = selectList.get(i).getCompressPath();
            Log.e("7788", compressPath);
            API.AddFile(RizhiActivity.this, new File(compressPath),
                    tvZhuti.getText().toString(), shijian, tv_beizhu.getText().toString(), tvJinzhanyaodian.getText().toString()
                    , new Okhttp.Objectcallback() {
                        @Override
                        public void onsuccess(String st) {
                            Log.e("zzzz", "xx" + st);
                            Rizhi rizhi = JSONUtils.parseJSON(st, Rizhi.class);
                            if (rizhi.getError()==0) {
                                Toast.makeText(RizhiActivity.this, ""+rizhi.getMsg(), Toast.LENGTH_SHORT).show();
                           finish();
                            } else {
                                Toast.makeText(RizhiActivity.this, ""+rizhi.getMsg(), Toast.LENGTH_SHORT).show();
                            }

                        }

                        @Override
                        public void onFalia(int code, String errst) {
                            Log.e("zzzz", "xx" + errst);
                            Toast.makeText(RizhiActivity.this, ""+errst , Toast.LENGTH_SHORT).show();
                        }
                    });
//            Bitmap bitmap = BitmapFactory.decodeFile(compressPath);
//            String cv = Utils.BitmapToString(bitmap);
//            photo = new Photo_Bean();
//            photo.setImgCode(cv);
//            long s = System.currentTimeMillis()+i*2;
//            Date date = new Date(s);
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//
//            String format = sdf.format(date);
//            photo.setImgName(format + ".jpg");
//            photo_been.add(photo);
        }
//        jsosns = JSONUtils.listToJson(photo_been);
//        qingqiu();

    }

    //    public void tuijian() {
//        if (TextUtils.isEmpty(textView7.getText().toString())) {
//            Toast.makeText(this, "请输入订单号", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        if (TextUtils.isEmpty(tv_beizhu.getText().toString())) {
//            Toast.makeText(this, "请输入问题描述", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        if (selectList.size() == 0) {
//            jsosns = "";
//            showdialog();
//            qingqiu();
//        } else {
//            showdialog();
//            shangchuan();
//        }
//    }
//    public void qingqiu() {
//        API.WTJ(textView7.getText().toString(), tv_beizhu.getText().toString(), jsosns, id, LoginName, new Okhttp.Objectcallback() {
//            @Override
//            public void onsuccess(String st) {
//                Log.e(TAG, "xx" + st);
//                if (dialog != null) {
//                    dialog.dismiss();
//                }
//                if (!TextUtils.isEmpty(st)) {
//                    QS_FH_Bean qs_fh_bean = JSONUtils.parseJSON(st, QS_FH_Bean.class);
//                    if (qs_fh_bean.isSucess()) {
//                        Toast.makeText(RizhiActivity.this, "问题件递交成功", Toast.LENGTH_SHORT).show();
//                        PictureFileUtils.deleteCacheDirFile(RizhiActivity.this);
//                        finish();
//                    } else {
//                        Toast.makeText(RizhiActivity.this, "问题件递交失败", Toast.LENGTH_SHORT).show();
//                    }
//
//                } else {
//                    Toast.makeText(RizhiActivity.this, "系统错误", Toast.LENGTH_SHORT).show();
//                }
//            }
////
//
//
//            @Override
//            public void onFalia(int code, String errst) {
//                if (dialog != null) {
//                    dialog.dismiss();
//                }
//                Toast.makeText(RizhiActivity.this, "网络错误"+errst, Toast.LENGTH_SHORT).show();
//            }
//        });
//    }
    KProgressHUD dialog;

    public void showdialog() {
        dialog = KProgressHUD.create(RizhiActivity.this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在上传中，请稍候")
                .setCancellable(true)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();
    }

    @OnClick({R.id.img_back, R.id.save_address})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.save_address:
                shangchuan();
                break;
        }
    }
}
